const userService = require('../../../services/userService');
const jwt = require('jsonwebtoken'); // 导入 jsonwebtoken 库
const getAllUsersController = async (req, res) => {
    try {
        const users = await userService.getAllUsersService();
        res.status(200).json({ success: true, data: users });
    } catch (err) {
        res.status(404).json({ error: false, message: err.message });
    }
}
const getUser = async (req, res) => {
    try {
        const userId = req.params.id;
        const user = await userService.getUserById(userId);
        res.status(200).json({ success: true, data: user });
    } catch (err) {
        res.status(404).json({ error: false, message: err.message });
    }
};

const login = async (req, res) => {
    try {
        const { username, password } = req.body;
        // 检查用户名和密码是否为空
        if (!username || !password) {
            return res.status(400).json({ error: false, message: '用户名和密码不能为空' });
        }

        //这个获取到 的就是user对象
        const user = await userService.getUserByUsername(username);
        //检查用户是否存在
        if (!user) {
            return res.status(401).json({ error: false, message: '用户名不存在' })
        }

        //检查密码是否正确
        if (user.password !== password) {
            return res.status(401).json({ error: false, message: '密码错误' })
        }
        //生成token
        const token = jwt.sign(
            {
                id: user.id,
                username: user.username
            },
            process.env.JWT_SECRET1 || 'mysecretkey',
            //设置token过期时间
            { expiresIn: '72h' }
        )
        // 返回响应
        res.json({
            code: 200,
            message: '登录成功',
            data: {
                token,
                user: {
                    userId: user.user_id,
                }
            }
        })
    }
    catch (err) {
        res.status(404).json({ error: false, message: err.message });
    }
}
const addUser = async (req, res) => {
    try {
        const newUser = await userService.addUser(req.body);
        res.status(201).json({ success: true, data: newUser });
    } catch (err) {
        res.status(400).json({ error: false, message: err.message });
    }
}
module.exports = {
    getUser,
    login,
    getAllUsersController,
    addUser
};